package com.pitaya.winwine.service;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.pitaya.framework.common.BCSFileUtils;
import com.pitaya.framework.common.ErrorInfo;
import com.pitaya.framework.common.StringUtils;
import com.pitaya.winwine.domain.Wine;
import com.pitaya.winwine.repository.WineAdviceRepository;
import com.pitaya.winwine.repository.WineRepository;

@Service
public class WineService {
	
	private Log log = LogFactory.getLog(WineService.class);
	
	@Autowired
	private WineRepository wineRepository;
	
	@Autowired
	private WineAdviceRepository wineAdviceRepository;

	@Transactional
	public Wine createWine(Wine wine, MultipartFile file) {
		if (file.getSize() > 0) {
			String extension = FilenameUtils.getExtension(file.getOriginalFilename());
			if ((extension == null) || ("jpg|jpeg|png".indexOf(extension.toLowerCase()) == -1)) {
				wine.setErrorInfo(ErrorInfo.INVALID_UPLOAD_FORMAT);
				return wine;
			}
			if (file.getSize() > 1048576L) {
				wine.setErrorInfo(ErrorInfo.INVALID_UPLOAD_SIZE);
				return wine;
			}
			StringBuilder fileName = new StringBuilder();
			fileName.append("/wine/").append(StringUtils.getUUID()).append(".")
				.append(FilenameUtils.getExtension(file.getOriginalFilename()));
			InputStream inputStream;
			try {
				inputStream = file.getInputStream();
				wine.setPicUrl(BCSFileUtils.uploadFile(inputStream, fileName.toString(), file.getSize()));
			} catch (IOException e) {
				this.log.error(e.getMessage());
			} finally {
				inputStream = null;
			}
			IOUtils.closeQuietly(inputStream);
		}
		Date date = new Date();
		wine.setCreateTime(date);
		wine.setEditTime(date);
		wine.setEditor(wine.getCreator());
		wineRepository.save(wine);
		return wine;
	}
	
}
